app.controller("gateCtr", ["$scope", "$http", "$filter", "$rootScope", "$stateParams", "$modal", "$timeout", "lodash",
function($scope, $http, $filter, $rootScope, $stateParams, $modal, $timeout, lodash) {
    $scope.currentUrlPath = "http://10.130.24.237:8096/api/v1";
    $scope.info = {
        areaList: config_area_list,
        sltAreaName: lodash.first(config_area_list).areaName,
        programeList: [],    // 全部工程
        sltProgrameItem: "",
        apiList: [],   //全部接口
        sltApiItem: "",
        methodList: [],
        sltMethodItem: "",
        versionList: [
            {"id": 1, "name": "1.0.0", "crtname": "1.0.0"},
            {"id": 2, "name": "2.0.0", "crtname": "2.0.0"}
        ],
        sltVersionItem: {"id": 1, "name": "1.0.0", "crtname": "1.0.0"},
        paramsList: [],
        sltParamItem: "",
        showApiLoading: false,
        showMethodLoading: false,
        showParamLoading: false,
        tabList: [
            {"name": "输入", "type": "in", "active": true},
            {"name": "返回值", "type": "out", "active": false},
            {"name": "结果对比", "type": "diff", "active": false}
        ],
        isShowJson: false,
        paramsData: "",
        jsonData: "",
        jsonString: "",
        testRtnData: "",
        isDiff: false,
        leftObj: "",
        rightObj: "",
        isText: false,
        updateJson: true,
        updateBtnDisabled: false
    }

    getAllPrograme();
    
    // 获取所有工程
    function getAllPrograme() {
        var url = $scope.currentUrlPath + "/sgService/getSys";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                var programeDataArray = new Array();
                angular.forEach(result.data, function(res) {
                    programeDataArray.push({"crtname": res, "value": res});
                });
                $scope.info.programeList = programeDataArray;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    // 切换工程--获取接口
    $scope.selectProgrameFun = function(item) {
        $scope.info.showApiLoading = true;
        $scope.info.sltApiItem = "";
        var url = $scope.currentUrlPath + "/sgService/getServices?sys="+ item.value;
        $http.get(url).success(function(result) {
            $scope.info.showApiLoading = false;
            if(result.code == "0") {
                var selectApiList = new Array();
                angular.forEach(result.data, function(res) {
                    res.otherValue = res.sDesc ? (res.sDesc.split("<")[1] ? (res.sDesc.split("<")[1].split(">")[0]) : res.sDesc) : res.name;
                    res.crtname = res.name;
                    selectApiList.push(res);
                });
                $scope.info.apiList = selectApiList;
            } else {
                $rootScope.toasterErrorInfo("获取接口数据错误！");
            }
        });
    };

    // 切换接口--获取方法
    $scope.selectApiFun = function(item) {
        $scope.info.showMethodLoading = true;
        $scope.info.sltMethodItem = "";
        var url = $scope.currentUrlPath + "/method/getMethods?serviceId="+ item.id +"&type=sg&isParam=1";
        $http.get(url).success(function(result) {
            $scope.info.showMethodLoading = false;
            if(result.code == "0") {
                var selectMethodList = new Array();
                angular.forEach(result.data, function(res) {
                    res.crtname = res.name;
                    res.otherValue = res.mDesc;
                    selectMethodList.push(res);
                });
                $scope.info.methodList = selectMethodList;
            } else {
                $rootScope.toasterErrorInfo("获取方法错误！");
            }
        });
    };

    // 切换区域
    $scope.switchArea = function(area) {
        console.log(area);
        $scope.info.sltAreaName = area.areaName;
    };

    // 选中方法调用参数数据
    $scope.selectMethodFun = function(item) {
        // 方法默认参数
        var paramsOfMethod = [];
        if(item.params.length) {
            var defaultParamItem = [item.params[0].params];
            defaultParamItem.crtname = "默认参数";
            defaultParamItem.isDefault = true;
            paramsOfMethod.push(defaultParamItem);
        }
        // $scope.info.paramsList = paramsOfMethod;
        // 调用查询参数的方法
        getParamsByMethodId(paramsOfMethod);
    };

    // 根据方法调用参数数据
    function getParamsByMethodId(paramsOfMethod) {
        $scope.info.showParamLoading = true;
        $scope.info.sltParamItem = "";
        var url = $scope.currentUrlPath + "/params/getParam?relateId="+ $scope.info.sltMethodItem.id;
        $http.get(url).success(function(result) {
            $scope.info.showParamLoading = false;
            if(result.code == "0") {
                angular.forEach(result.data, function(param) {
                    if(param.paramJson) {
                        var params = [param.paramJson.params];
                        params.id = param.id;
                        params.crtname = param.name;
                        paramsOfMethod.push(params);
                    }
                });
                $scope.info.paramsList = paramsOfMethod;
            } else {
                $scope.info.paramsList = paramsOfMethod;
                $rootScope.toasterErrorInfo("获取参数数据失败！");
            }
        });
    };

    // 选择参数
    $scope.selectParamFun = function(item) {
        $scope.info.updateBtnDisabled = item.isDefault || false;
        $scope.info.updateJson = false;
        $scope.info.paramsData = item[0];
        $scope.info.jsonData = item[0];
        $scope.info.updateJson = true;
    };

    // 切换tab页
    $scope.tabClick = function(tab) {
        switch(tab.type) {
            case "in":
                $scope.info.isDiff = false;
                $scope.info.jsonData = $scope.info.paramsData ? $scope.info.paramsData : "";
                $scope.info.jsonString = $filter("json")($scope.info.jsonData);
                break;
            case "out":
                $scope.info.isDiff = false;
                $scope.info.jsonData = $scope.info.testRtnData ? $scope.info.testRtnData : "";
                $scope.info.jsonString = $filter("json")($scope.info.jsonData);
                break;
            case "diff":
                $scope.info.isDiff = true;
                $scope.info.isText = false;
                $scope.info.leftObj = $filter("json")($scope.info.paramsData ? $scope.info.paramsData : "");
                $scope.info.rightObj = $filter("json")($scope.info.testRtnData);
                break;
        }
    }

    // 调试
    $scope.testClick = function() {
        if(!$scope.info.jsonData) {
            $rootScope.toasterWarningInfo("输入数据不能为空！");
            return false;
        }
        var url = "../data/outParam.json";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.testRtnData = result.data;
                $scope.info.jsonData = result.data;
                // 设置对比tab选中
                var diffItem = lodash.findWhere($scope.info.tabList, {type: "diff"});
                diffItem.active = true;
                $scope.info.isDiff = true;
                $scope.info.isText = false;
                $scope.info.leftObj = $filter("json")($scope.info.paramsData ? $scope.info.paramsData.parameter.rtn.data : "");
                $scope.info.rightObj = $filter("json")($scope.info.testRtnData);
            } else {
                $rootScope.toasterErrorInfo("调试失败！");
            }
        });
    };

    // 添加参数
    $scope.addParamItem = function() {
        if(!$scope.info.jsonData) {
            $rootScope.toasterWarningInfo("添加参数数据不能为空！");
            return false;
        }
        openModal("add");
    };

    // 修改参数
    $scope.updateParamItem = function() {
        if(!$scope.info.jsonData) {
            $rootScope.toasterWarningInfo("修改参数数据不能为空！");
            return false;
        }
        openModal("update", $scope.info.sltParamItem);
    };

    // 打开modal框
    function openModal(type, paramItem) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/servicegate/tpl/addsgmodal.html"),
            controller: "addParamCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                type: function () {
                    return type;
                },
                paramItem: function () {
                    return paramItem;
                }
            }
        });

        modalInstance.result.then(function (paramTitle) {
            type == "add" ? addItemToParamsList(paramTitle) : updateItemToParamsList(paramTitle);
        }, function (reason) {
            console.log("关闭modal");
        });
    }

    // 新增参数数据到参数列表中
    function addItemToParamsList(paramTitle) {
        var addParamItem = {
            "id": "",
            "name": paramTitle,
            "paramJson": {
                "params": $scope.info.jsonData
            },
            "relateId": $scope.info.sltMethodItem.id,
            "rtn": {}
        };
        var url = $scope.currentUrlPath + "/params/saveParam";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(addParamItem),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if(result.code == "0") {
                addParamItem.id = result.data.id;
                var newParamItem = [addParamItem.paramJson.params];
                newParamItem.crtname = addParamItem.name;
                $scope.info.paramsList.push(newParamItem);
                $rootScope.toasterSuccessInfo("添加成功！");
            } else {
                $rootScope.toasterErrorInfo("添加参数失败！");
            }
        });
    }

    // 修改参数
    function updateItemToParamsList(paramTitle) {
        var updateParamItem = {
            "id": $scope.info.sltParamItem.id,
            "name": paramTitle,
            "paramJson": {
                "params": $scope.info.jsonData
            },
            "relateId": $scope.info.sltMethodItem.id,
            "rtn": {}
        };
        var url = $scope.currentUrlPath + "/params/saveParam";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(updateParamItem),
            headers: {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                var currentItem = lodash.findWhere($scope.info.paramsList, {id: $scope.info.sltParamItem.id});
                currentItem.name = paramTitle;
                currentItem.crtname = paramTitle;
                currentItem.paramJson = $scope.info.jsonData;
                $rootScope.toasterSuccessInfo("修改成功！");
            } else {
                $rootScope.toasterErrorInfo("修改参数失败！");
            }
        });
    }

    // 切换文本-JSON
    $scope.switchChange = function(status) {
        $scope.info.isText = status;
        if(status) {
            $scope.info.jsonString = $filter("json")($scope.info.jsonData);
        } else {
            $scope.info.jsonData = JSON.parse($scope.info.jsonString);
        }
    };
    

}]);

app.controller("addParamCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "type", "paramItem", function ($scope, $rootScope, $modalInstance, $http, type, paramItem) {
    $scope.info = {
        title: type == "add" ? "添加参数" : "修改参数",
        paramsTitle: paramItem ? paramItem.crtname : ""
    }

    $scope.createClick = function () {
        if(!$scope.info.paramsTitle) {
            $rootScope.toasterWarningInfo("参数名称不能为空！");
            return false;
        }
        $modalInstance.close($scope.info.paramsTitle);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);
